import {createRouter, createWebHistory} from 'vue-router'

const routes = [
    {
        path: '/',
        redirect: '/products'
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Auth/Login.vue')
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../views/Auth/Register.vue')
    },
    {
        path: '/products',
        name: 'Products',
        component: () => import('../views/Products/List.vue')
    },
    {
        path: '/products/:id',
        name: 'ProductDetail',
        component: () => import('../views/Products/Detail.vue')
    },
    {
        path: '/cart',
        name: 'Cart',
        component: () => import('../views/Cart.vue'),
        meta: {requiresAuth: true}
    },
    {
        path: '/orders',
        name: 'Orders',
        component: () => import('../views/Orders.vue'),
        meta: {requiresAuth: true}
    },
    {
        path: '/address',
        name: 'Address',
        component: () => import('../views/address/AddressList.vue'),
        meta: {requiresAuth: true}
    },
    {
        path: '/admin',
        name: 'Admin',
        component: () => import('../views/Admin.vue'),
        meta: {requiresAdmin: true}
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const isAuthenticated = localStorage.getItem('token')
    const isAdmin = localStorage.getItem('isAdmin') === 'true'

    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login')
    } else if (to.meta.requiresAdmin && !isAdmin) {
        next('/products')
    } else {
        next()
    }
})

export default router
